package com.whisperarts.financer.app.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.whisperarts.financer.app.Application;
import com.whisperarts.financer.model.account.Account;

public class OpenAccountAction extends Action implements 
ISelectionListener, IWorkbenchAction {

	private final IWorkbenchWindow window;
	public final static String ID = "com.whisperarts.financer.app.actions.openAccount";
	private IStructuredSelection selection;


	public OpenAccountAction(IWorkbenchWindow window) {
		this.window = window;
		setId(ID);
		setText("&Open account");
		setToolTipText("Open transactions for selected account");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Application.PLUGIN_ID, ISharedImages.IMG_OBJS_INFO_TSK));
		window.getSelectionService().addSelectionListener(this);
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
		if (incoming instanceof IStructuredSelection) {
			selection = (IStructuredSelection) incoming;
			setEnabled(selection.size() == 1 &&
					selection.getFirstElement() instanceof Account);
		} else {
			setEnabled(false);
		}
	}

	@Override
	public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}

	@Override
	public void run() {
		ActionsFactory.doOpenAccountAction((Account) selection.getFirstElement(), window);
	}
}
